<template>
  <el-dialog v-model="visible" title="选择用户" width="70%">
    <PlusSearch
      v-model="queryform"
      :columns="formConfig"
      :show-number="2"
      label-width="80"
      label-position="right"
      class="mb-xs"
      @search="initData(true)"
      @reset="initData(true)"
    />
    <PureTable
      v-if="visible"
      ref="tableRef"
      border
      show-overflow-tooltip
      highlight-current-row
      :max-height="300"
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :pagination="pagination"
      :row-style="{ cursor: 'pointer' }"
      row-key="userId"
      @page-size-change="initData"
      @page-current-change="initData(false)"
      @current-change="handleSelectionChange"
      @selection-change="handleSelectionChange"
    >
      <template #chooseStatus="{ row }">
        <el-icon size="18"
          ><Check
            v-if="(chooseItem as any)?.userId == row.userId"
            class="text-primary"
        /></el-icon>
      </template>
      <template #status="{ row }">
        <el-tag v-if="row.status == 0" type="primary">正常</el-tag>
        <el-tag v-else type="danger">停用</el-tag>
      </template>
    </PureTable>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, nextTick, defineEmits, onMounted } from "vue";
import { useTableConfig } from "@/utils/tableConfig";
import { type PlusColumn, PlusSearch } from "plus-pro-components";
import { getUserList } from "@/api/user";
import { Check } from "@element-plus/icons-vue";

const visible = ref(false);
const isMultiple = ref(true);

/* 表格数据操作 */
const tableRef = ref(null);

/* 查询数据 */
const formConfig: PlusColumn[] = [
  { label: "账号/用户名/角色", prop: "searchVal", labelWidth: 150 }
];
const queryform = ref({ searchVal: "" });

/* 表格数据 */
const { pagination } = useTableConfig();
const tableData = ref([]);
const loading = ref(false);

const columns = ref([]);
const getCoumns = () => {
  const arr = [
    { label: "账号", prop: "userName" },
    { label: "用户名称", prop: "nickName" },
    {
      label: "角色",
      prop: "roleName"
    },
    {
      label: "组织",
      prop: "depts",
      formatter: ({ depts }) => {
        if (depts) {
          const arr = depts.map(item => item.deptName);
          return arr.join(", ");
        }
        return "";
      }
    },
    { label: "账号状态", prop: "status", slot: "status" },
    { label: "添加时间", prop: "createTime", width: 180 }
  ];
  let obj = {};
  obj = isMultiple.value
    ? { type: "selection" }
    : {
        label: "",
        prop: "chooseStatus",
        slot: "chooseStatus",
        width: 40
      };

  return [obj, ...arr];
};

const initData = (needInit = true) => {
  loading.value = true;
  if (needInit) {
    pagination.currentPage = 1;
  }
  const params = {
    ...queryform.value,
    pageSize: pagination.pageSize,
    pageNum: pagination.currentPage
  };
  getUserList(params)
    .then(({ rows, total }) => {
      tableData.value = rows;
      pagination.total = Number(total);
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

// 选择操
const chooseItem = ref({});
const handleSelectionChange = val => {
  /**如果是多选，返回的是就是对象数组。
   * 如果是单选，返回的就是单独的对象
   * **/
  chooseItem.value = val;
};

/* 弹窗操作 */
const handleCancel = () => {
  visible.value = false;
};

const emit = defineEmits(["confirm"]);

const handleSubmit = () => {
  emit("confirm", chooseItem.value);
  visible.value = false;
};
/* 初始化 */
const show = (chooseData?: any, multiple = true) => {
  initData();
  visible.value = true;
  isMultiple.value = multiple;
  columns.value = getCoumns();
  nextTick(() => {
    const { setCurrentRow, clearSelection } = tableRef?.value?.getTableRef();

    clearSelection();
    setCurrentRow();
  });
};
defineExpose({ show });
</script>
